package com.zj.weather.utils;

import java.util.Random;

/**
 * Created by ZhaoJie on 2018/7/22.
 */

public class RandomUtils {

    /**
     * 获取[min, max)内的随机数，越大的数概率越小
     */
    public static float getDownRandFloat(float min, float max) {
        float bigend = ((min + max) * max) / 3f;
        float x = getRandom(min, bigend);
        int sum = 0;
        for (int i = 0; i < max; i++) {
            sum += (max - i);
            if (sum > x) {
                return i;
            }
        }
        return min;
    }

    /**
     * [min, max)
     */
    public static float getRandom(float a, float b) {
        float min = Math.min(a, b);
        float max = Math.max(a, b);
        return (float) (min + Math.random() * (max - min));
    }

    /**
     * 必须取[0,1]之间的float
     */
    public static float fixAlpha(float alpha) {
        if (alpha > 1f) {
            return 1f;
        }
        if (alpha < 0f) {
            return 0f;
        }
        return alpha;
    }

    //增量算法，k =0时平均分布，k<0时数越大概率越小，K>0时数越大概率越大；
    public static float getRandMax(float a, float k) {
        float n = (int) (Math.pow(Math.random(), k) * a);
        return n;
    }

    // 获得0--n之内的不等概率随机整数，0概率最大，1次之，以此递减，n最小
    public static int getAnyRandInt(int n) {
        int max = n + 1;
        int bigend = ((1 + max) * max) / 2;
        Random rd = new Random();
        int x = Math.abs(rd.nextInt() % bigend);
        int sum = 0;
        for (int i = 0; i < max; i++) {
            sum += (max - i);
            if (sum > x) {
                return i;
            }
        }
        return 0;
    }

}
